package com.cll.pmis.common.security;

import com.cll.pmis.common.Strategy;
import com.cll.pmis.common.annotation.HasPerms;
import com.cll.pmis.common.annotation.HasRoles;
import com.cll.pmis.common.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chenliangliang
 * @date 2018/6/24
 */
@Slf4j
public class SecurityInterceptor implements HandlerInterceptor {


    /**
     * 在请求处理之前进行调用（Controller方法调用之前
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        log.debug("拦截器...");
        HandlerMethod method = (HandlerMethod) o;
        SysUser sysUser = SecurityUtil.getUser(httpServletRequest);
        HasPerms hasPerms = method.getMethodAnnotation(HasPerms.class);
        boolean permsFlag = true;
        if (hasPerms != null) {
            if (sysUser==null){
                handleError(httpServletRequest,httpServletResponse,"您还未登录");
                return false;
            }
            String[] perms = hasPerms.value();
            Strategy strategy = hasPerms.strategy();

            if (strategy == Strategy.AND) {
                permsFlag = sysUser.hasAllPerms(perms);
            } else if (strategy == Strategy.OR) {
                permsFlag = sysUser.inPerms(perms);
            } else {
                permsFlag = sysUser.noPerms(perms);
            }
        }

        boolean roleFlag = true;
        HasRoles hasRoles = method.getMethodAnnotation(HasRoles.class);
        if (hasRoles != null) {
            if (sysUser==null){
                handleError(httpServletRequest,httpServletResponse,"您还未登录");
                //throw new PmisException("您还未登录");
                return false;
            }
            String[] roles = hasRoles.value();
            Strategy strategy = hasRoles.strategy();

            if (strategy == Strategy.AND) {
                roleFlag = sysUser.hasRole(roles);
            } else if (strategy == Strategy.OR) {
                roleFlag = sysUser.inRoles(roles);
            } else {
                roleFlag = sysUser.noRoles(roles);
            }
        }
        if (permsFlag && roleFlag) {
            return true;
        }else {
            handleError(httpServletRequest,httpServletResponse,"您无权限访问，请联系超级管理员");
            return false;
        }
    }


    private void handleError(HttpServletRequest request, HttpServletResponse response,String msg) throws ServletException, IOException {
        request.setAttribute("error",msg);
        request.getRequestDispatcher("/auth/error").forward(request,response);
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //System.out.println("postHandle");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //System.out.println("afterCompletion");
    }
}
